<template>
  <!-- 项目逻辑设置容器 -->
  <div class="project-logic-container">
    <!-- 内部包装容器 -->
    <div class="project-logic-inner-wrap">
      <!-- 头部区域 -->
      <div class="logic-header">
        <div class="logic-header-left">
          <span class="logic-title-bar"></span>
          <span class="logic_title">{{ $t("form.logic.logicSettingsLabel") }}</span>
          <el-tooltip
            :content="$t('form.logic.logicDescription')"
            effect="dark"
            placement="right"
          >
            <el-icon class="logic-title-help">
              <ele-QuestionFilled />
            </el-icon>
          </el-tooltip>
          <el-text
            :type="isSave"
            class="save-message"
            size="default"
          >
            {{ saveMessage }}
          </el-text>
        </div>
        <!-- 逻辑类型过滤器 -->
        <div class="logic-actions">
          <el-select
            v-model="logicTypeFilterVal"
            class="mr10 logic-type-filter"
            clearable
            collapse-tags
            collapse-tags-tooltip
            multiple
            size="default"
            @change="handleLogicTypeFilterValChange"
          >
            <el-option
              v-for="item in logicTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <!-- 添加逻辑按钮 -->
          <el-button
            :loading="isLoading"
            class="ml10"
            icon="ele-Plus"
            size="default"
            type="primary"
            @click="addLogicHandle"
          >
            <span class="label">{{ $t("form.logic.addLogicLabel") }}</span>
          </el-button>
          <!-- 清空所有逻辑按钮 -->
          <el-popconfirm
            :title="$t('form.logic.cleanAll')"
            @confirm="() => (logicList = [])"
          >
            <template #reference>
              <el-button size="default">
                <el-icon :size="16">
                  <ele-Delete />
                </el-icon>
                {{ $t("form.logic.cleanLogic") }}
              </el-button>
            </template>
          </el-popconfirm>
        </div>
      </div>
      <!-- 逻辑项列表容器 -->
      <div
        v-loading="loading"
        class="logic-item-container"
      >
        <el-empty v-if="isDataEmpty" />
        <el-scrollbar
          v-if="allProjectItemList.length"
          :height="windowHeight - 200"
        >
          <!-- 逻辑项循环 -->
          <div
            v-for="(logicItem, index) in filteredLogicList"
            v-show="shouldShowLogicItem(logicItem)"
            :key="logicItem.id"
            class="logic-item"
          >
            <el-card
              class="logic-card"
              shadow="never"
            >
              <!-- 删除逻辑项按钮 -->
              <div class="logic-item-delbtn">
                <el-popconfirm
                  :title="$t('form.logic.confirmDeleteLabel')"
                  @confirm="handleRemoveLogicItem(index)"
                >
                  <template #reference>
                    <el-button
                      link
                      type="danger"
                    >
                      <el-icon :size="16">
                        <ele-Delete />
                      </el-icon>
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
              <!-- 条件列表 -->
              <el-row
                v-for="(cItem, cIndex) in logicItem.conditionList"
                :key="cItem"
                :gutter="10"
                align="middle"
                class="mt5"
                justify="center"
                type="flex"
              >
                <el-col
                  :span="3"
                  class="text-center"
                >
                  <span
                    v-if="cIndex === 0"
                    class="text-left"
                  >
                    {{ $t("form.logic.ifFormComponentLabel") }}
                  </span>
                  <!-- 关系选择器 -->
                  <el-select
                    v-else
                    v-model="cItem.relation"
                    :disabled="cIndex !== 1"
                    @change="relationChangeHandle"
                  >
                    <el-option
                      :label="$t('form.logic.andLabel')"
                      value="AND"
                    />
                    <el-option
                      :label="$t('form.logic.orLabel')"
                      value="OR"
                    />
                  </el-select>
                </el-col>
                <!-- 条件项选择 -->
                <el-col :span="7">
                  <select-wrap
                    :placeholder="$t('form.logic.select')"
                    :text="componentMap.get(cItem.formItemId || '')"
                    @click="event => handleConditionItemClick(event, cItem)"
                  />
                </el-col>
                <!-- 表达式选择 -->
                <el-col :span="5">
                  <select-wrap
                    :placeholder="$t('form.logic.condition')"
                    :text="expressionMap[cItem.expression || '']"
                    @click="event => handleExpressionClick(event, cItem)"
                  />
                </el-col>
                <!-- 选项值输入 -->
                <el-col :span="6">
                  <!-- 下拉问题选项 -->
                  <FormOptionSelect
                    v-if="['RADIO', 'CHECKBOX', 'SELECT', 'IMAGE_SELECT'].includes(getFormItemIdType(cItem.formItemId))"
                    v-model="cItem.optionValue"
                    :disabled="cItem.expression && ['notNull', 'isNull'].includes(cItem.expression)"
                    :item="getFormItemOptions(cItem.formItemId)"
                    :multiple="
                      'CHECKBOX' === getFormItemIdType(cItem.formItemId) &&
                      cItem.expression &&
                      ['eq', 'ne'].includes(cItem.expression)
                    "
                    :placeholder="$t('form.logic.option')"
                    allow-create
                    class="width100"
                    clearable
                    default-first-option
                    filterable
                    size="default"
                    valueProp="value"
                  ></FormOptionSelect>
                  <!-- 评分数字输入 -->
                  <el-input-number
                    v-else-if="getFormItemIdType(cItem.formItemId) === 'RATE'"
                    v-model="cItem.optionValue"
                    :min="0"
                  />
                  <FormCascaderOptionSelect
                    v-else-if="getFormItemIdType(cItem.formItemId) === 'CASCADER'"
                    v-model="cItem.optionValue"
                    :disabled="cItem.expression && ['notNull', 'isNull'].includes(cItem.expression)"
                    :item="getFormItemOptions(cItem.formItemId)"
                    :placeholder="$t('form.logic.option')"
                    class="width100"
                    clearable
                    size="default"
                    valueProp="value"
                  />
                  <!-- 普通文本输入 -->
                  <el-input
                    v-else
                    v-model="cItem.optionValue"
                    :disabled="cItem.expression && ['notNull', 'isNull'].includes(cItem.expression)"
                    size="default"
                  ></el-input>
                </el-col>
                <!-- 条件操作按钮 -->
                <el-col :span="3">
                  <el-button
                    link
                    type="primary"
                    @click="addConditionHandle(logicItem, cItem)"
                  >
                    <el-icon size="18">
                      <ele-CirclePlus />
                    </el-icon>
                  </el-button>
                  <el-button
                    v-if="cIndex !== 0"
                    class="remove"
                    link
                    type="primary"
                    @click="removeConditionHandle(logicItem, index, cIndex)"
                  >
                    <el-icon size="18">
                      <ele-Remove />
                    </el-icon>
                  </el-button>
                </el-col>
              </el-row>
              <!-- 触发动作列表 -->
              <el-row
                v-for="(trigger, tindex) in logicItem.triggerList"
                :key="trigger"
                align="middle"
                class="mt5"
                type="flex"
              >
                <el-col :span="3">
                  <span class="result-text">{{ $t("form.logic.thenLabel") }}</span>
                </el-col>
                <el-col
                  :span="6"
                  class="text-center"
                >
                  <!-- 触发类型选择 -->
                  <select-wrap
                    :placeholder="$t('form.logic.type')"
                    :text="logicTypeMap[trigger.type || '']"
                    class="ml10"
                    style="width: 80%"
                    @click="event => handleTriggerTypeClick(event, trigger)"
                  />
                </el-col>
                <el-col :span="10">
                  <!-- 目标项选择 -->
                  <select-wrap
                    v-if="!['finish', 'showOption', 'checkOption'].includes(trigger.type)"
                    :placeholder="$t('form.logic.question')"
                    :text="componentMap.get(trigger.formItemId || '')"
                    class="ml10"
                    style="width: 50%"
                    @click="event => handleTriggerItem(event, logicItem, trigger)"
                  />
                  <span
                    v-if="trigger.type === 'show'"
                    class="result-text"
                  >
                    {{ $t("form.logic.otherwiseNotDisplayLabel") }}
                  </span>
                  <span
                    v-if="trigger.type === 'jump'"
                    class="result-text"
                  >
                    {{ $t("form.logic.otherwiseShowNextLabel") }}
                  </span>
                  <!-- 选项级联选择器 -->
                  <el-cascader
                    v-if="['showOption', 'checkOption'].includes(trigger.type)"
                    v-model="trigger.optionValue"
                    :options="getFormOptionItems"
                    :placeholder="$t('form.logic.question')"
                    :props="{ multiple: true }"
                    class="ml10"
                    clearable
                    collapse-tags
                    size="default"
                    style="width: 50%"
                  ></el-cascader>
                </el-col>
                <!-- 触发动作操作按钮 -->
                <el-col :span="4">
                  <el-button
                    link
                    type="primary"
                    @click="addTriggerItemHandle(logicItem)"
                  >
                    <el-icon size="18">
                      <ele-CirclePlus />
                    </el-icon>
                  </el-button>
                  <el-button
                    v-if="tindex !== 0"
                    class="remove"
                    link
                    type="primary"
                    @click="removeTriggerItemHandle(logicItem, index, tindex)"
                  >
                    <el-icon size="18">
                      <ele-Remove />
                    </el-icon>
                  </el-button>
                </el-col>
              </el-row>
            </el-card>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <!-- 选择弹窗组件 -->
    <select-popover
      v-if="conditionProjectItemList.length"
      ref="conditionSelectPopoverRef"
      :option-props="{
        value: 'formItemId',
        label: 'textLabel'
      }"
      :options="conditionProjectItemList"
      filterable
      @change="handleSelectPopover"
    />
    <select-popover
      v-if="allProjectItemList.length"
      ref="targetItemPopoverRef"
      :option-props="{
        value: 'formItemId',
        label: 'textLabel'
      }"
      :options="allProjectItemList"
      filterable
      @change="handleSelectPopover"
    />
    <select-popover
      v-if="logicTypeOptions.length"
      ref="logicTypePopoverRef"
      :options="logicTypeOptions"
      @change="handleSelectPopover"
    />
    <select-popover
      v-if="expressionOptions.length"
      ref="expressionPopoverRef"
      :options="expressionOptions"
      @change="handleSelectPopover"
    />
  </div>
</template>

<script lang="ts" name="ProjectLogic" setup>
// 导入必要的依赖
import { computed, nextTick, onActivated, onMounted, ref, watch } from "vue";
import { jsonSimpleClone, removeHtmlTag } from "@/views/formgen/utils";
import { getFormLogicRequest, listProjectItemRequest, saveFormLogicRequest, UserFormItemEntity } from "@/api/project/form";
import { i18n } from "@/i18n";
import FormOptionSelect from "@/views/components/FormOptionSelect/index.vue";
import FormCascaderOptionSelect from "@/views/components/FormOptionSelect/cascader.vue";

import { useRoute } from "vue-router";
import { debounce } from "lodash-es";
import {
  ChangeSelect,
  Condition,
  DEFAULT_LOGIC_ITEM,
  FORM_ITEM_COMPARE_TYPE,
  FormItemOptions,
  LogicItem,
  LogicType,
  RelationType,
  SUPPORT_LOGIC_COMPONENTS,
  Trigger
} from "@/views/form/logic/BasicLogic/types";
import SelectPopover from "../components/SelectPopover.vue";
import SelectWrap from "../components/SelectWrap.vue";
import { MessageUtil } from "@/utils/messageUtil";
import { formDesign } from "@/views/formgen/components/FormDesign/hooks/useFormDesign";
import { formItemConvertData } from "@/views/formgen/utils/convert";
import { useWindowSize } from "@vueuse/core";
import { logicConfigStore } from "./useLogicConfig";

// 状态管理
const saveMessage = ref("");
const isSave = ref<"info" | "success" | "warning" | "error">("info");
const isLoading = ref(false);
const formKey = ref<string>("");
const logicTypeFilterVal = ref<LogicType[]>([]);
const isDataEmpty = ref<boolean>(false);
const loading = ref(true);
const loadEnd = ref(false);

// 组件引用
const conditionSelectPopoverRef = ref<InstanceType<typeof SelectPopover> | null>(null);
const logicTypePopoverRef = ref<InstanceType<typeof SelectPopover> | null>(null);
const expressionPopoverRef = ref<InstanceType<typeof SelectPopover> | null>(null);
const targetItemPopoverRef = ref<InstanceType<typeof SelectPopover> | null>(null);
const changeSelectObj = ref<ChangeSelect | null>(null);

// 数据
const allProjectItemList = ref<UserFormItemEntity[]>([]);
const { logicList } = logicConfigStore;
const componentMap = new Map<string, string>();

// 计算属性
const getFormOptionItems = computed(() => {
  return allProjectItemList.value
    .filter((item: UserFormItemEntity) => {
      return ["RADIO", "CHECKBOX", "SELECT", "IMAGE_SELECT"].includes(item.type);
    })
    .map((item: UserFormItemEntity) => {
      const options = item.scheme?.config?.options;
      return {
        value: item.formItemId,
        label: item.textLabel,
        children: options?.map((option: any) => ({
          value: option.value,
          label: option.label ? removeHtmlTag(option.label) : ""
        }))
      };
    });
});

// 优化性能的计算属性
const filteredLogicList = computed(() => {
  if (!logicTypeFilterVal.value.length) {
    return logicList.value;
  }
  return logicList.value.filter(item => logicTypeFilterVal.value.includes(item.triggerList[0]?.type));
});

// 方法定义
const setOptionDefaultVal = (cItem: Condition) => {
  if ("CHECKBOX" === getFormItemIdType(cItem.formItemId) && cItem.expression && ["eq", "ne"].includes(cItem.expression)) {
    cItem.optionValue = [];
  } else if ("CHECKBOX" === getFormItemIdType(cItem.formItemId)) {
    cItem.optionValue = "";
  } else {
    cItem.optionValue = null;
  }
};

const getFormItemIdType = (formItemId: string | null): string => {
  if (!formItemId) return "";
  return formItemId.replace(/\d+/, "").toUpperCase();
};

const getFormItemOptions = (formItemId: string | null): FormItemOptions | undefined => {
  const formItem = allProjectItemList.value.find(item => item.formItemId === formItemId);
  return formItem ? { field: formItem } : undefined;
};

// 处理逻辑类型过滤值变化
const handleLogicTypeFilterValChange = (val: LogicType[]) => {
  if (!val.length) {
    isDataEmpty.value = logicList.value.length === 0;
    return;
  }
  const hasMatchingItem = logicList.value.some(item => val.includes(item.triggerList[0]?.type));
  isDataEmpty.value = !hasMatchingItem;
};

// 处理关系变化
const relationChangeHandle = (val: string, logicItem: LogicItem) => {
  logicItem.conditionList.forEach(item => {
    item.relation = val as RelationType;
  });
};

// 处理选择弹窗
const handleSelectPopover = () => {
  if (!changeSelectObj.value) return;

  const { type, obj } = changeSelectObj.value;

  switch (type) {
    case "condition":
    case "expression":
      if ("expression" in obj) {
        setOptionDefaultVal(obj);
      }
      break;
    case "trigger":
      if ("type" in obj && ["finish", "showOption", "checkOption"].includes(obj.type)) {
        obj.formItemId = null;
      }
      break;
  }
};

const route = useRoute();
const { height: windowHeight } = useWindowSize();

// 生命周期钩子
onMounted(() => {
  formKey.value = route.query.key as string;
  loadData();
});

onActivated(() => {
  queryProjectItems();
});

// 优化数据加载
const loadData = async () => {
  try {
    loading.value = true;
    await Promise.all([queryProjectLogic(), queryProjectItems()]);
  } catch (error) {
    MessageUtil.error(i18n.global.t("form.logic.loadError"));
  } finally {
    loading.value = false;
    nextTick(() => {
      loadEnd.value = true;
    });
  }
};

// 查询项目逻辑
const queryProjectLogic = () => {
  getFormLogicRequest({ formKey: formKey.value }).then(res => {
    if (res.data) {
      logicList.value = res.data.scheme ? res.data.scheme : [];
    }
    if (!res.data || !logicList.value || !logicList.value.length) {
      isDataEmpty.value = true;
    }
  });
};

// 查询项目项
const queryProjectItems = async () => {
  let list = drawingList.value.map(item => {
    let data: any = formItemConvertData(item, formKey.value);
    data!.textLabel = removeHtmlTag(data.label);
    return data;
  }) as UserFormItemEntity[];

  if (!list || !list.length) {
    const res = await listProjectItemRequest({ key: formKey.value });
    list = res.data;
  }

  if (list) {
    allProjectItemList.value = list.filter((item: UserFormItemEntity) => {
      return item.type !== "PAGINATION";
    });

    conditionProjectItemList.value = jsonSimpleClone(allProjectItemList.value).filter((item: UserFormItemEntity) => {
      return SUPPORT_LOGIC_COMPONENTS.includes(item.type);
    });

    // 生成组件映射
    allProjectItemList.value.forEach((item: UserFormItemEntity) => {
      componentMap.set(item.formItemId as string, item.textLabel);
    });
  }
};

// 优化保存逻辑
const saveProjectLogic = debounce(async (logicList: LogicItem[]) => {
  try {
    isLoading.value = true;
    isSave.value = "info";
    saveMessage.value = i18n.global.t("form.logic.handling");

    const data = { formKey: formKey.value, scheme: logicList };
    await saveFormLogicRequest(data);

    isSave.value = "success";
    saveMessage.value = i18n.global.t("form.logic.isSave");
  } catch (error) {
    isSave.value = "error";
    saveMessage.value = i18n.global.t("form.logic.saveError");
    MessageUtil.error(i18n.global.t("form.logic.saveError"));
  } finally {
    isLoading.value = false;
  }
}, 430);

// 逻辑类型选项
const logicTypeOptions = ref([
  {
    value: "show",
    label: i18n.global.t("form.logic.showLabel")
  },
  {
    value: "jump",
    label: i18n.global.t("form.logic.jumpLabel")
  },
  {
    value: "finish",
    label: i18n.global.t("form.logic.finishLabel")
  },
  {
    value: "showOption",
    label: i18n.global.t("form.logic.showOptionLabel")
  },
  {
    value: "checkOption",
    label: i18n.global.t("form.logic.checkOption")
  }
]);

// 逻辑类型映射
const logicTypeMap: any = ref(
  logicTypeOptions.value.reduce((acc: any, curr: any) => {
    acc[curr.value] = curr.label;
    return acc;
  }, {})
);

// 表达式选项
const expressionOptions = ref(FORM_ITEM_COMPARE_TYPE);

// 表达式映射
const expressionMap: any = ref(
  expressionOptions.value.reduce((acc: any, curr: any) => {
    acc[curr.value] = curr.label;
    return acc;
  }, {})
);

const conditionProjectItemList = ref([]);

// 优化事件处理
const handleTriggerItem = (event: MouseEvent, logicItem: LogicItem, target: Trigger) => {
  const selectedFormItemList = logicItem.conditionList
    .map((item: Condition) => item.formItemId)
    .filter((id): id is string => id !== null);

  checkRef(targetItemPopoverRef, () => {
    targetItemPopoverRef.value?.handleClick(event, target, "formItemId", selectedFormItemList);
  });
};

const handleRemoveLogicItem = (index: number) => {
  logicList.value.splice(index, 1);
};

const addConditionHandle = (logicItem: LogicItem, cItem: Condition) => {
  logicItem.conditionList.push({
    expression: null,
    formItemId: null,
    optionValue: null,
    relation: cItem.relation
  });
};

const removeConditionHandle = (logicItem: LogicItem, logicIndex: number, index: number) => {
  logicItem.conditionList.splice(index, 1);
};

const addTriggerItemHandle = (logicItem: LogicItem) => {
  logicItem.triggerList.push({
    type: "show",
    formItemId: null
  });
};

const removeTriggerItemHandle = (logicItem: LogicItem, logicIndex: number, index: number) => {
  logicItem.triggerList.splice(index, 1);
};

const addLogicHandle = () => {
  isLoading.value = true;
  const newLogicItem = jsonSimpleClone(DEFAULT_LOGIC_ITEM);
  newLogicItem.id = new Date().getTime();
  logicList.value.push(newLogicItem);
  isDataEmpty.value = false;
};

const handleConditionItemClick = (event: MouseEvent, cItem: Condition) => {
  changeSelectObj.value = {
    type: "condition",
    obj: cItem
  };
  checkRef(conditionSelectPopoverRef, () => {
    conditionSelectPopoverRef.value?.handleClick(event, cItem, "formItemId");
  });
};

const handleExpressionClick = (event: MouseEvent, cItem: Condition) => {
  if (!cItem.formItemId) {
    MessageUtil.warning(i18n.global.t("form.logic.question"));
    return;
  }
  changeSelectObj.value = {
    type: "expression",
    obj: cItem
  };
  const type = cItem.formItemId.replace(/\d+/, "").toUpperCase();
  const notShowKey: string[] = [];

  expressionOptions.value.forEach((item: any) => {
    if (!item.types.includes(type)) {
      notShowKey.push(item.value);
    }
  });

  checkRef(expressionPopoverRef, () => {
    expressionPopoverRef.value?.handleClick(event, cItem, "expression", notShowKey);
  });
};

const handleTriggerTypeClick = (event: MouseEvent, trigger: Trigger) => {
  changeSelectObj.value = {
    type: "trigger",
    obj: trigger
  };
  checkRef(logicTypePopoverRef, () => {
    logicTypePopoverRef.value?.handleClick(event, trigger, "type");
  });
};

const { drawingList } = formDesign;
// 监听逻辑列表变化
watch(
  logicList,
  val => {
    if (val && loadEnd.value) {
      saveProjectLogic(val);
    }
  },
  { deep: true }
);

// 优化模板中的条件渲染
const shouldShowLogicItem = (logicItem: LogicItem) => {
  return logicTypeFilterVal.value.length === 0 || logicTypeFilterVal.value.includes(logicItem.triggerList[0]?.type);
};

// 优化组件引用检查
const checkRef = (ref: any, action: () => void) => {
  if (!ref.value) {
    console.warn("Component reference is null");
    return;
  }
  action();
};
</script>

<style lang="scss" scoped>
.logic-header {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .logic-header-left {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .logic_title {
    font-size: var(--el-font-size-base);
    color: var(--el-text-color-regular);
    text-align: left;
  }

  .save-message {
    margin-left: 10px;
    width: 150px;
  }

  .logic-title-bar {
    width: 4px;
    height: 24px;
    background: var(--el-color-primary);
    border-radius: 2px;
    margin-right: 10px;
  }

  .logic-title-help {
    color: var(--el-text-color-secondary);
    font-size: 18px;
    cursor: pointer;
  }

  .logic-type-filter {
    width: 150px;
  }
}

// 无逻辑容器样式
.not-logic-container {
  .el-icon-circle-plus-outline {
    font-size: 20px;
  }

  .label {
    font-size: 18px;
  }
}

// 逻辑项容器样式
.logic-item-container {
  height: 100%;

  .tips {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }

  .label {
    font-size: 15px;
  }

  .remove {
    color: var(--el-color-danger);
  }

  // 图标样式
  .el-icon-circle-plus-outline,
  .el-icon-remove-outline {
    font-size: 24px;
  }

  // 逻辑项样式
  .logic-item {
    position: relative;

    .logic-item-delbtn {
      display: flex;
      justify-content: flex-end;
    }
  }

  // 逻辑卡片样式
  .logic-card {
    --el-card-padding: 8px;
    border-radius: 10px;
    background-color: var(--el-color-primary-light-10);
    margin-top: 10px;
  }

  // 结果文本样式
  .result-text {
    line-height: 32px;
    margin-left: 20px;
    vertical-align: top;
  }
}
</style>
